﻿//===========================================================================================================================
// Cuberry - http://www.cuberry.net
// Copyright (c) 2012
// by Peacequare® - Amir Moussa
//===========================================================================================================================
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License 
// as published by the Free Software Foundation, either version 3 of the License, or any later version.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// This program is distributed in the hope that it will be useful.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//===========================================================================================================================

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using P2.Cuberry.Framework.BOLBase;
using P2.Cuberry.Framework.Security;
using P2.Cuberry.Framework.Helper;
using P2.Cuberry.Framework.Helper.Configuration;
using P2.Cuberry.Modules.Framework.UserGroup.DAL;


namespace P2.Cuberry.Modules.Framework.UserGroup.BusinessEntities
{
    public class UserGroupSpecialRight : BizObject, INotifyPropertyChanged//, IEditableObject
    {

        #region Constructors

        public UserGroupSpecialRight()
        {
            Modified = false;
        }


        public UserGroupSpecialRight(int keyUserGroupID, string keyModuleName, string keyDialogName, string keyControlName, int keySubMenuItemID, int keyAccessRight, int keyStatusID)
        {
            this._UserGroupID = keyUserGroupID;
            this._ModuleName = keyModuleName;
            this._DialogName = keyDialogName;
            this._ControlName = keyControlName;
            this._AccessRight = keyAccessRight;
            this.StatusID = keyStatusID;
            Modified = false;
        }


        public UserGroupSpecialRight(DAL.XSecUserRightsSpecial UserGroupSpecialRight)
        {
            Load(UserGroupSpecialRight);
        }

        #endregion


        #region Members

        private static DateTime _lastCacheUpdate = DateTime.MinValue;

        int _UserGroupID = -1;
        public int UserGroupID
        {
            get { return _UserGroupID; }
            set
            {
                if (value != _UserGroupID)
                {
                    _UserGroupID = value;
                    Modified = true;
                }
            }
        }

        string _ModuleName = String.Empty;
        public string ModuleName
        {
            get { return _ModuleName; }
            set
            {
                if (value != _ModuleName)
                {
                    _ModuleName = value;
                    Modified = true;
                }
            }
        }

        string _DialogName = String.Empty;
        public string DialogName
        {
            get { return _DialogName; }
            set
            {
                if (value != _DialogName)
                {
                    _DialogName = value;
                    Modified = true;
                }
            }
        }

        string _ControlName = String.Empty;
        public string ControlName
        {
            get { return _ControlName; }
            set
            {
                if (value != _ControlName)
                {
                    _ControlName = value;
                    Modified = true;
                }
            }
        }

        string _ControlType = String.Empty;
        public string ControlType
        {
            get { return _ControlType; }
            set
            {
                if (value != _ControlType)
                {
                    _ControlType = value;
                    Modified = true;
                }
            }
        }
       
        int? _AccessRight = -1;
        public int? AccessRight
        {
            get { return _AccessRight; }
            set
            {
                if (value != _AccessRight)
                {
                    _AccessRight = value;
                    Modified = true;
                }
            }
        }

        //int _StatusID = -1;
        //public int StatusID
        //{
        //    get { return _StatusID; }
        //    set
        //    {
        //        if (value != _StatusID)
        //        {
        //            _StatusID = value;
        //            Modified = true;
        //        }
        //    }
        //}

        #endregion


        #region Computed Properties

        //public string StatusName
        //{
        //    get
        //    {
        //        var tempStatus = P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus.GetItemForModule(this.ModuleName, this.StatusID);
        //        if (tempStatus == null)
        //        {
        //            tempStatus = new P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus() { StatusID = this.StatusID };
        //        }
        //        return tempStatus.StatusNameCur;
        //    }
        //}

        #endregion


        #region Read Operations

        public void Load(DAL.XSecUserRightsSpecial sourceEntity)
        {
            try
            {
                if (sourceEntity != null)
                {
                    this.UserGroupID = sourceEntity.UserGroupID;
                    this.ModuleName = sourceEntity.ModuleName;
                    this.DialogName = sourceEntity.DialogName;
                    this.ControlName = sourceEntity.ControlName;
                    this.ControlType = sourceEntity.ControlType;
                    this.AccessRight = sourceEntity.AccessRight;                    

                    //Default Fields                
                    this.CreatedBy = sourceEntity.CreatedBy;
                    this.CreatedOn = sourceEntity.CreatedOn;
                    this.EditedBy = sourceEntity.EditedBy;
                    this.EditedOn = sourceEntity.EditedOn;
                    //this.Timestamp = sourceEntity.TStamp;
                    //this.StatusID = sourceEntity.StatusID.GetValueOrDefault(P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus.GetInitialStatus(this.EntityName).StatusID);
                    this.StatusID = P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus.GetInitialStatus(this.EntityName).StatusID;
                }
                else
                {
                    this.UserGroupID = -1;
                    this.ModuleName = String.Empty;
                    this.DialogName = String.Empty;
                    this.ControlName = String.Empty;
                    this.ControlType = String.Empty;
                    this.AccessRight = -1;
                    
                    //Default Fields
                    this.CreatedBy = String.Empty;
                    this.EditedBy = String.Empty;
                    P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus initStatus = P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus.GetInitialStatus(this.EntityName);
                    this.StatusID = initStatus.StatusID;
                }
                Modified = false;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }


        internal P2TransactionMessage FillMyObject()
        {
            P2TransactionMessage tMsg = new P2TransactionMessage();

            try
            {
                string connectionString = ConfigurationSetUp.GetEntConnectionString("Business", Properties.Settings.Default.EntityResources);
                using (UserGroupDataContext db = new UserGroupDataContext(connectionString))
                {
                    var UserGroupSpecialRights = from UserGroupSpecialRightItem in db.XSecUserRightsSpecials
                                                 where UserGroupSpecialRightItem.UserGroupID == this._UserGroupID
                                          && UserGroupSpecialRightItem.ModuleName == this._ModuleName
                                          && UserGroupSpecialRightItem.DialogName == this._DialogName
                                          && UserGroupSpecialRightItem.ControlName == this._ControlName
                                          && UserGroupSpecialRightItem.StatusID == this.StatusID
                                                 
                                                 select UserGroupSpecialRightItem;

                    if (UserGroupSpecialRights.Count() > 0)
                    {
                        foreach (var UserGroupSpecialRight in UserGroupSpecialRights)
                        {
                            Load(UserGroupSpecialRight);
                        }
                    }
                }
                tMsg.TransactionStatus = "green";
                tMsg.MessageText = "TMsg_FillMyObjectSuceeded";
            }
            catch (Exception ex) //AM:TC!!
            {
                tMsg.TransactionStatus = "red";
                tMsg.MessageText = "Error_Error";
                tMsg.MessageFreeText = ex.Message;
                P2ExceptionHandler.LogException(ex, this);
            }
            this.MessageStack.Add(tMsg);
            return tMsg;
        }

        #endregion

        
        
        #region Update Operations

        public P2MessageStack InsertAndUpdate(bool checkDoublicate, UserGroupDataContext db)
        {
            P2TransactionMessage tMsg = new P2TransactionMessage();

            tMsg.TransactionStatus = "green";
            P2MessageStack MessageStack = new P2MessageStack();
            
            if (tMsg.TransactionStatus == "green")
            {
                try
                {
                    if (tMsg.TransactionStatus == "green")
                    {
                        if (this.StatusID == -1) this.StatusID = 2001;
                        P2.Cuberry.Framework.Security.AccessPermissions ap = new P2.Cuberry.Framework.Security.AccessPermissions();

                        if (string.IsNullOrEmpty(this.CreatedBy)) this.CreatedBy = ap.UserID;
                        this.EditedBy = ap.UserID;
                        DAL.XSecUserRightsSpecial editedItem;
                        var SpecialRights = from sr in db.XSecUserRightsSpecials
                                            where sr.UserGroupID == this.UserGroupID
                                            && sr.ModuleName == this.ModuleName
                                            && sr.DialogName == this.DialogName
                                            && sr.ControlName == this.ControlName
                                            && sr.StatusID == this.StatusID //.GetValueOrDefault(0)
                                            select sr;

                        if (SpecialRights.Count()  == 0)
                        {
                            editedItem = new DAL.XSecUserRightsSpecial()
                            {
                                ModuleName = this.ModuleName,
                                UserGroupID = this.UserGroupID,
                                ControlName = this.ControlName,
                                AccessRight = this.AccessRight,
                                ControlType = this.ControlType,
                                DialogName = this.DialogName,

                                //Default Fields
                                CreatedBy = User.Current.UserID,
                                CreatedOn = DateTime.Now,
                                EditedBy = User.Current.UserID,
                                EditedOn = DateTime.Now,
                                StatusID = this.StatusID
                            };
                            db.XSecUserRightsSpecials.AddObject(editedItem);                            
                        }
                        else
                        {
                            //Update Data
                            editedItem = SpecialRights.First();
                            editedItem.ModuleName = this.ModuleName;
                                editedItem.UserGroupID = this.UserGroupID;
                                editedItem.ControlName = this.ControlName;
                                editedItem.StatusID = this.StatusID; //.GetValueOrDefault(0);
                                editedItem.AccessRight = this.AccessRight;
                                editedItem.ControlType = this.ControlType;
                                editedItem.DialogName = this.DialogName;
                                
                                //Default Fields
                                editedItem.EditedBy = User.Current.UserID;
                                editedItem.EditedOn = DateTime.Now;
                                editedItem.StatusID = this.StatusID;

                                //track changes!
                                //this.SaveChangeLog(-3 Fields-);  
                        }
                        db.SaveChanges();

                        Load(editedItem);
                    }                    
                }
                catch (Exception ex) //AM:TC!!
                {
                    MessageStack.Add(new P2TransactionMessage("red", P2Translator.GetResource("Error_Error")));
                    P2ExceptionHandler.LogException(ex, this);
                }
            }
            return MessageStack;
        }

        
        public void Cancel()
        {
            try
            {
                this.StatusID = 999903;
                string connectionString = ConfigurationSetUp.GetEntConnectionString("Business", Properties.Settings.Default.EntityResources);
                using (UserGroupDataContext db = new UserGroupDataContext(connectionString))
                {
                    var UserGroupSpecialRight = (from UserGroupSpecialRightItem in db.XSecUserRightsSpecials
                                                 where UserGroupSpecialRightItem.UserGroupID.Equals(this.UserGroupID)
                                     && UserGroupSpecialRightItem.ModuleName.Equals(this.ModuleName)
                                     && UserGroupSpecialRightItem.DialogName.Equals(this.DialogName)
                                     && UserGroupSpecialRightItem.ControlName.EndsWith(this.ControlName)
                                                 select UserGroupSpecialRightItem).First();

                    db.SaveChanges();
                }
                this.FillMyObject();
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }

        #endregion


        #region Copy Operations

        public UserGroupSpecialRight GetCopy()
        {
            try
            {
                UserGroupSpecialRight newItem = new UserGroupSpecialRight();
                newItem.UserGroupID = this.UserGroupID;
                newItem.ModuleName = this.ModuleName;
                newItem.DialogName = this.DialogName;
                newItem.ControlName = this.ControlName;
                newItem.ControlType = this.ControlType;
                newItem.AccessRight = this.AccessRight;
                newItem.StatusID = this.StatusID;
                return newItem;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
                return null;
            }
        }


        public void UpdateFrom(UserGroupSpecialRight sourceItem)
        {
            try
            {
                this.UserGroupID = sourceItem.UserGroupID;
                this.ModuleName = sourceItem.ModuleName;
                this.DialogName = sourceItem.DialogName;
                this.ControlName = sourceItem.ControlName;
                this.ControlType = sourceItem.ControlType;
                this.AccessRight = sourceItem.AccessRight;
                this.StatusID = sourceItem.StatusID;
                this.Modified = sourceItem.Modified;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }

        }
        
        #endregion


        #region Validation
        //Empty
        #endregion
        

        #region Property Changed

        public event PropertyChangedEventHandler PropertyChanged;
      

        private void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler Handler = PropertyChanged;
            if (Handler != null) Handler(this, new PropertyChangedEventArgs(propertyName));
        }


        public void OnAllPropertiesChanged()
        {
            OnPropertyChanged("UserGroupID");
            OnPropertyChanged("ModuleName");
            OnPropertyChanged("DialogName");
            OnPropertyChanged("ControlName");
            OnPropertyChanged("ControlType");
            OnPropertyChanged("SubMenuItemID");
            OnPropertyChanged("AccessRight");
            OnPropertyChanged("StatusID");
        }

        #endregion

                
        #region Validator

        public override P2Validator Validator
        {
            get
            {
                if (_validator == null)
                    _validator = new P2Validator(Properties.Settings.Default.ModuleName, this.EntityName, "UserGroupID", this);
                return _validator;
            }
        }

        #endregion        

        
        public UserGroupRight ParentUserGroupRight { set; get; }

        public static ObservableCollection<UserGroupSpecialRight> GetUserGroupSpecialRightsforHeader(UserGroupRight userGroupRight, PropertyChangedEventHandler onChange)
        {
            try
            {
                ObservableCollection<UserGroupSpecialRight> itemsCollection = new ObservableCollection<UserGroupSpecialRight>();
                string connectionString = ConfigurationSetUp.GetEntConnectionString("Business", Properties.Settings.Default.EntityResources);
                using (UserGroupDataContext db = new UserGroupDataContext(connectionString))
                {

                    var UserGroupSpecialRightItems = from ugsrItem in db.XSecUserRightsSpecials
                                                     where ugsrItem.UserGroupID == userGroupRight.UserGroupID
                                                      && ugsrItem.ModuleName == userGroupRight.ModuleName
                                                     select ugsrItem;
                    if (UserGroupSpecialRightItems.Count() > 0)
                    {
                        foreach (var userGroupSpecialRightItem in UserGroupSpecialRightItems)
                        {
                            itemsCollection.Add(new UserGroupSpecialRight(userGroupSpecialRightItem) { ParentUserGroupRight = userGroupRight });
                        }
                    }

                }
                return itemsCollection;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", "UserGroupSpecialRight", System.Reflection.MethodInfo.GetCurrentMethod().Name));
                return null;
            }
        }
        
        internal static List<string> GetDialogNamesforModule(string moduleName)
        {
            try
            {
                List<string> dialognames = new List<string>();
                string connectionString = ConfigurationSetUp.GetEntConnectionString("Business", Properties.Settings.Default.EntityResources);
                using (UserGroupDataContext db = new UserGroupDataContext(connectionString))
                {
                    var UIItems = (from UIItem in db.XConfigUIControls
                                   where UIItem.ModuleName == moduleName
                                   select UIItem);
                    if (UIItems.Count() > 0)
                    {
                        foreach (var UIItem in UIItems)
                        {
                            if (!dialognames.Contains(UIItem.DialogName))
                                dialognames.Add(UIItem.DialogName);
                        }
                    }
                }
                return dialognames;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", "UserGroupSpecialRight", System.Reflection.MethodInfo.GetCurrentMethod().Name));
                return null;
            }
        }


        internal static List<string> GetControlNamesforModule(string moduleName)
        {
            try
            {
                List<string> controlnames = new List<string>();
                string connectionString = ConfigurationSetUp.GetEntConnectionString("Business", Properties.Settings.Default.EntityResources);
                using (UserGroupDataContext db = new UserGroupDataContext(connectionString))
                {
                    var UIItems = (from UIItem in db.XConfigUIControls
                                   where UIItem.ModuleName == moduleName
                                   select UIItem);
                    if (UIItems.Count() > 0)
                    {
                        foreach (var UIItem in UIItems)
                        {
                            if (!controlnames.Contains(UIItem.ControlName))
                                controlnames.Add(UIItem.ControlName);
                        }
                    }
                }
                return controlnames;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", "UserGroupSpecialRight", System.Reflection.MethodInfo.GetCurrentMethod().Name));
                return null;
            }
        }
        

    }
}
